<?php
namespace common\logic;
use common\models\BannerModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;
class BannerLogic extends Logic
{
	/**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return BannerModel::find();
    }
    
	public function BannnerSave(BannerModel $model)
    {
        $this->saveFile($model, 'banner');
        $rs = $model->save();
        return $rs;
    }
    
    /**
     * 保存上传文件banner、广告位
     *
     * @param \common\models\HouseModel $model
     * @param                           $key
     */
    protected function saveFile(BannerModel $model, $key)
    {
        if ($_FILES && !empty($_FILES['BannerModel']['name'][$key])) {
            $filePath = "/upload/$key/";
            $fileName = $filePath . uniqid() . '.' . pathinfo($_FILES['BannerModel']['name'][$key], PATHINFO_EXTENSION);
            $filePath = \Yii::getAlias('@webroot') . $filePath;
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $savePath = \Yii::getAlias('@webroot') . $fileName;
            if (move_uploaded_file($_FILES['BannerModel']['tmp_name'][$key], $savePath)) {
                $model->$key = $fileName;
            }
        }
    }
    
    public function houseSave(BannerModel $model)
    {
        $this->saveFile($model, 'banner');
        $rs = $model->save();
        return $rs;
    }
	
	public function getAdv($region)
    {
        /**
         * @var $banners HouseModel[]
         */
//      $banners = $this->getQuery(['region' => $region],['id' => SORT_DESC])->andWhere("banner>''")->limit(6)->all();
//		$banners = $this->getQuery(['region' => 18],['id' => SORT_DESC])->limit(6)->all();
		$banners = $this->getQuery(['region' => $region],[],[],['id' => SORT_DESC])->limit(6)->all();
        $newBanners = [];
        foreach ($banners as $banner) {
            $newBanners[] = ["id"=>$banner->houseid,"banner"=>$banner->banner];
        }

        return ['banners' => $newBanners];
    }
}
?>